package com.cq.hd.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cq.hd.common.entity.mq.ActiveBrowseMsg;
import com.cq.hd.common.enums.biz.OrderStateEnum;
import com.cq.hd.common.enums.biz.PromotionTypeEnum;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.Throw;
import com.cq.hd.member.api.TbBusinessApi;
import com.cq.hd.member.api.vo.BusinessVo;
import com.cq.hd.order.api.TbOrderApi;
import com.cq.hd.order.api.dto.OrderDto;
import com.cq.hd.order.api.vo.OrderAvatarVo;
import com.cq.hd.product.api.dto.*;
import com.cq.hd.product.api.vo.ActiveBrowsePageVo;
import com.cq.hd.product.api.vo.ActiveBrowseVo;
import com.cq.hd.product.mapper.*;
import com.cq.hd.product.po.TbActiveBrowsePo;
import com.cq.hd.product.po.TbActiveBrowseStatisticsPo;
import com.cq.hd.product.po.TbActiveGroupBuyPo;
import com.cq.hd.product.service.TbActiveBrowseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cq.hd.product.service.TbActiveGroupBuyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 活动浏览记录表 服务实现类
 * </p>
 *
 * @author mYunYu
 * @since 2023-12-01
 */
@Slf4j
@Service
public class TbActiveBrowseServiceImpl extends ServiceImpl<TbActiveBrowseMapper, TbActiveBrowsePo> implements TbActiveBrowseService {

    private final Random random = new Random();

    @Autowired
    private TbActiveBrowseStatisticsMapper activeBrowseStatisticsMapper;

    @Autowired
    private TbActiveDiscountMapper activeDiscountMapper;

    @Autowired
    private TbActiveStepPriceMapper activeStepPriceMapper;

    @Autowired
    private TbActiveRedPacketMapper activeRedPacketMapper;

    @Autowired
    private TbBusinessApi businessApi;

    @Autowired
    private TbOrderApi orderApi;

    @Autowired
    private TbActiveGroupBuyService activeGroupBuyService;

    @Override
    public Page<ActiveBrowsePageVo> pageActiveBrowse(ActiveBrowsePageDto activeBrowsePageDto) {
        PageHelper.startPage(activeBrowsePageDto.getPageNum(), activeBrowsePageDto.getPageSize());
        List<ActiveBrowsePageVo> activeBrowsePageVos = baseMapper.listByDto(activeBrowsePageDto);
        if (!CollectionUtils.isEmpty(activeBrowsePageVos)) {
            List<Long> activeIds = activeBrowsePageVos.stream().map(ActiveBrowsePageVo::getId).collect(Collectors.toList());
            List<Long> businessIds = activeBrowsePageVos.stream().map(ActiveBrowsePageVo::getBusinessId).collect(Collectors.toList());

            // 查询多件多折列表
            Map<Long, List<ActiveDiscountSonDto>> tbActiveDiscountPoMap = new HashMap<>();
            List<ActiveDiscountSonDto> tbActiveDiscountPos = activeDiscountMapper.listByActiveIds(activeIds);
            if (!CollectionUtils.isEmpty(tbActiveDiscountPos)) {
                tbActiveDiscountPoMap = tbActiveDiscountPos.stream().collect(Collectors.groupingBy(ActiveDiscountSonDto::getActiveId));
            }

            // 查询新人首单红包数据
            Map<Long, ActiveRedPacketSonDto> activeRedPacketSonDtoMap = new HashMap<>();
            List<ActiveRedPacketSonDto> activeRedPacketSonDtoList = activeRedPacketMapper.listByActiveIds(activeIds);
            if (!CollectionUtils.isEmpty(activeRedPacketSonDtoList)) {
                activeRedPacketSonDtoMap = activeRedPacketSonDtoList.stream().collect(Collectors.toMap(ActiveRedPacketSonDto::getActiveId, Function.identity(), (k1, k2) -> k2));
            }

            // 查询阶梯价格列表
            Map<Long, List<ActiveStepPriceSonDto>> activeStepPriceSonDtoMap = new HashMap<>();
            List<ActiveStepPriceSonDto> activeStepPriceSonDtos = activeStepPriceMapper.listByActiveIds(activeIds);
            if (!CollectionUtils.isEmpty(activeStepPriceSonDtos)) {
                activeStepPriceSonDtoMap = activeStepPriceSonDtos.stream().collect(Collectors.groupingBy(ActiveStepPriceSonDto::getActiveId));
            }

            // 查询商家数据
            Map<Long, BusinessVo> businessMap = new HashMap<>();
            List<BusinessVo> businessPageVos = businessApi.listByIds(businessIds).unpack();
            if (!CollectionUtils.isEmpty(businessPageVos)) {
                businessMap = businessPageVos.stream().collect(Collectors.toMap(BusinessVo::getId, Function.identity(), (k1, k2) -> k2));
            }

            // 查询活动浏览数
            Map<Long, List<TbActiveBrowseStatisticsPo>> tbActiveBrowseStatisticsPoMap = new HashMap<>();
            List<TbActiveBrowseStatisticsPo> tbActiveBrowseStatisticsPos = activeBrowseStatisticsMapper.selectList(new QueryWrapper<TbActiveBrowseStatisticsPo>()
                    .eq("del_state", 0)
                    .in("active_id", activeIds));
            if (!CollectionUtils.isEmpty(tbActiveBrowseStatisticsPos)) {
                tbActiveBrowseStatisticsPoMap = tbActiveBrowseStatisticsPos.stream().collect(Collectors.groupingBy(TbActiveBrowseStatisticsPo::getActiveId));
            }

            // 查询浏览的活动的下单用户列表
            Map<Long, List<OrderAvatarVo>> orderAvatarMap = new HashMap<>();
            OrderDto orderDto = new OrderDto();
            orderDto.setActiveIds(activeIds);
            orderDto.setOrderStates(Arrays.asList(OrderStateEnum.WAIT_VERIFY.getValue(),
                    OrderStateEnum.VERIFYING.getValue(),
                    OrderStateEnum.FINISH.getValue(),
                    OrderStateEnum.VERIFIED.getValue()));
            List<OrderAvatarVo> orderAvatarVos = orderApi.listAvatarByDto(orderDto).unpack();
            if (!CollectionUtils.isEmpty(orderAvatarVos)) {
                orderAvatarMap = orderAvatarVos.stream().collect(Collectors.groupingBy(OrderAvatarVo::getActiveId));
            }

            for (ActiveBrowsePageVo activeBrowsePageVo : activeBrowsePageVos) {
                Long id = activeBrowsePageVo.getId();
                Long businessId = activeBrowsePageVo.getBusinessId();

                List<ActiveDiscountSonDto> activeDiscountSonDtos = tbActiveDiscountPoMap.get(id);
                if (!CollectionUtils.isEmpty(activeDiscountSonDtos)) {
                    activeBrowsePageVo.setActiveDiscount(activeDiscountSonDtos);
                }

                ActiveRedPacketSonDto activeRedPacketSonDto = activeRedPacketSonDtoMap.get(id);
                if (activeRedPacketSonDto != null) {
                    activeBrowsePageVo.setActiveRedPacket(activeRedPacketSonDto);
                }

                List<ActiveStepPriceSonDto> activeStepPriceSonDtoList = activeStepPriceSonDtoMap.get(id);
                if (!CollectionUtils.isEmpty(activeStepPriceSonDtoList)) {
                    activeBrowsePageVo.setActiveStepPrices(activeStepPriceSonDtoList);
                }

                BusinessVo businessVo = businessMap.get(businessId);
                if (businessVo != null) {
                    activeBrowsePageVo.setBusinessName(businessVo.getBusinessName());
                    activeBrowsePageVo.setBusinessShortName(businessVo.getBusinessShortName());
                    activeBrowsePageVo.setLogo(businessVo.getLogo());
                }

                List<TbActiveBrowseStatisticsPo> tbActiveBrowseStatisticsPoList = tbActiveBrowseStatisticsPoMap.get(id);
                if (!CollectionUtils.isEmpty(tbActiveBrowseStatisticsPoList)) {
                    activeBrowsePageVo.setBrowseNum(tbActiveBrowseStatisticsPoList.stream().mapToLong(TbActiveBrowseStatisticsPo::getBrowseNum).sum());
                }

                int buyNum = 0;
                List<OrderAvatarVo> orderAvatarVoList = orderAvatarMap.get(id);
                if (!CollectionUtils.isEmpty(orderAvatarVoList)) {
                    buyNum = orderAvatarVoList.stream().mapToInt(OrderAvatarVo::getOrderNum).sum();
                }
                activeBrowsePageVo.setBuyNum(buyNum);

                List<String> avatars = new ArrayList<>();
                if (!CollectionUtils.isEmpty(orderAvatarVoList)) {
                    if (orderAvatarVoList.size() > 3) {
                        // 随机取3条
                        for (int i = 0; i < 3; i++) {
                            avatars.add(orderAvatarVoList.get(random.nextInt(orderAvatarVoList.size())).getAvatar());
                        }
                    } else {
                        for (OrderAvatarVo orderAvatarVo : orderAvatarVoList) {
                            avatars.add(orderAvatarVo.getAvatar());
                        }
                    }
                }

                activeBrowsePageVo.setAvatars(avatars);
            }

            // 拼团活动标识
            processActivesGroupBuyTag(activeBrowsePageVos);
        }

        PageInfo<ActiveBrowsePageVo> pageInfo = new PageInfo<>(activeBrowsePageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }


    private void processActivesGroupBuyTag(List<ActiveBrowsePageVo> dataList) {
        if (CollectionUtils.isEmpty(dataList)) {
            return;
        }
        List<Long> activeIds = dataList.stream()
                .filter(e -> PromotionTypeEnum.GROUP_BUY.name().equals(e.getPromotionType()))
                .map(ActiveBrowsePageVo::getId)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(activeIds)) {
            return;
        }
        Map<Long, TbActiveGroupBuyPo> activeIdToGroupBuyInfo = activeGroupBuyService.listByActiveIds(activeIds)
                .stream()
                .collect(Collectors.toMap(TbActiveGroupBuyPo::getActiveId, Function.identity()));
        for (ActiveBrowsePageVo pageVo : dataList) {
            TbActiveGroupBuyPo groupBuyInfo = activeIdToGroupBuyInfo.get(pageVo.getId());
            if (groupBuyInfo != null) {
                pageVo.setPromotionLabel(groupBuyInfo.getGroupNum() + "人团");
            }
        }
    }

    @Override
    public Boolean clear(Long userId) {
        baseMapper.delete(new QueryWrapper<TbActiveBrowsePo>().eq("user_id", userId));
        return true;
    }

    @Override
    public Boolean removeActiveBrowseJob() {
        baseMapper.delete(new QueryWrapper<TbActiveBrowsePo>().le("browse_time", LocalDateTime.now().plusMonths(-2)));
        return true;
    }

    @Override
    public List<ActiveBrowseVo> listByDto(ActiveBrowseDto activeBrowseDto) {
        return baseMapper.listByActiveBrowseDto(activeBrowseDto);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean consumerActiveBrowseMsg(ActiveBrowseMsg activeBrowseMsg) {
        // 判断是否存在，存在更新，否则新增
        List<TbActiveBrowsePo> activeBrowsePos = baseMapper.selectList(new QueryWrapper<TbActiveBrowsePo>().eq("del_state", 0)
                .eq("active_id", activeBrowseMsg.getActiveId()).eq("user_id", activeBrowseMsg.getUserId())
                .orderByDesc("browse_time"));
        if (CollectionUtils.isEmpty(activeBrowsePos)) {
            TbActiveBrowsePo tbActiveBrowsePo = new TbActiveBrowsePo();
            BeanUtils.copyProperties(activeBrowseMsg, tbActiveBrowsePo);
            tbActiveBrowsePo.setCreateTime(LocalDateTime.now());
            int insert = baseMapper.insert(tbActiveBrowsePo);
            if (insert == 0) {
                log.error("增加活动浏览记录失败，activeBrowseMsg:{}", JSON.toJSONString(activeBrowseMsg));
                Throw.isBusinessException("增加活动浏览记录失败");
            }
        } else {
            TbActiveBrowsePo tbActiveBrowsePo = activeBrowsePos.get(0);
            tbActiveBrowsePo.setBrowseTime(activeBrowseMsg.getBrowseTime());
            tbActiveBrowsePo.setUpdateTime(LocalDateTime.now());
            int update = baseMapper.updateById(tbActiveBrowsePo);
            if (update == 0) {
                log.error("更新活动浏览记录失败，activeBrowseMsg:{}", JSON.toJSONString(activeBrowseMsg));
                Throw.isBusinessException("更新活动浏览记录失败");
            }
        }

        // 增加浏览记录统计数据
        List<TbActiveBrowseStatisticsPo> tbActiveBrowseStatisticsPos = activeBrowseStatisticsMapper.selectList(new QueryWrapper<TbActiveBrowseStatisticsPo>()
                .eq("del_state", 0)
                .eq("business_id", activeBrowseMsg.getBusinessId())
                .eq("active_id", activeBrowseMsg.getActiveId())
                .orderByDesc("update_time"));
        if (CollectionUtils.isEmpty(tbActiveBrowseStatisticsPos)) {
            TbActiveBrowseStatisticsPo tbActiveBrowseStatisticsPo = new TbActiveBrowseStatisticsPo();
            tbActiveBrowseStatisticsPo.setBusinessId(activeBrowseMsg.getBusinessId());
            tbActiveBrowseStatisticsPo.setActiveId(activeBrowseMsg.getActiveId());
            tbActiveBrowseStatisticsPo.setBrowseNum(1L);
            tbActiveBrowseStatisticsPo.setCreateTime(LocalDateTime.now());
            tbActiveBrowseStatisticsPo.setUpdateTime(LocalDateTime.now());
            int insert = activeBrowseStatisticsMapper.insert(tbActiveBrowseStatisticsPo);
            if (insert == 0) {
                log.error("增加活动浏览统计记录失败，activeBrowseMsg:{}", JSON.toJSONString(activeBrowseMsg));
                Throw.isBusinessException("增加活动浏览统计记录失败");
            }
        } else {
            TbActiveBrowseStatisticsPo tbActiveBrowseStatisticsPo = tbActiveBrowseStatisticsPos.get(0);
            int update = activeBrowseStatisticsMapper.addBrowseNum(tbActiveBrowseStatisticsPo.getId(), 1);
            if (update == 0) {
                log.error("更新活动浏览统计记录个数失败，activeBrowseMsg:{}", JSON.toJSONString(activeBrowseMsg));
                Throw.isBusinessException("更新活动浏览统计记录个数失败");
            }
        }

        return true;
    }
}
